#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
import re
import qqip
import sys
import numpy

curdir=sys.path[0]

province=['辽宁','江苏','湖北','四川','陕西','广东','河北','山西','河南','吉林','黑龙江','山东','安徽','浙江','福建','湖南','江西','贵州','云南','甘肃','青海','海南','台湾', '内蒙', '宁夏', '广西','西藏','新疆', '北京', '天津','上海','重庆','香港','澳门']

prov_short={'辽宁':'辽','江苏':'苏','湖北':'鄂','四川':'川','陕西':'陕','广东':'粤','河北':'冀','山西':'晋','河南':'豫','吉林':'吉','黑龙江':'黑','山东':'鲁','安徽':'皖','浙江':'浙','福建':'闽','湖南':'豫','江西':'赣','贵州':'黔','云南':'滇','甘肃':'甘','青海':'青','海南':'琼','台湾':'台', '内蒙':'蒙', '宁夏':'宁', '广西':'桂','西藏':'藏','新疆':'新', '北京':'京', '天津':'津','上海':'沪','重庆':'渝','香港':'港','澳门':'澳'}

procount=[]

for i in province:
	procount.append([i,[0,0]])

procount=dict(procount)

def IsInt( str ):
	""" Is the given string an integer?	"""
	ok = 1
	try:
		num = int(str)
	except ValueError:
		ok = 0
	return ok

delays=[]
delays_withip=[]

totalip=0

print 'Parsing files under data directory'
for i in os.listdir('%s/data'%curdir):
	if i!='.svn':
		f=open('%s/data/%s' % (curdir,i))
		g=f.readlines()
		f.close()
		finaltime=0
		finalip=''
		finallop=0
		for j in g:
			t=re.findall('\d+\.\d+ ms', j)
			ip=re.findall('\d+\.\d+\.\d+\.\d+',j)
			lop=j.strip().split()
			if IsInt(lop[0]):
				lop=int(lop[0])
			time=0
			for k in t:
				time=time+float(k.strip('ms').strip(' '))
			if len(t)>0:
				time=time/len(t)
			if time > 0:
				finaltime=time
				finalip=ip
				finallop=lop
		if finaltime>0:
	#		print '%d\t%16s  %d\t%s' % (finallop, i, int(round(finaltime)), list(set(finalip)))
			delays_withip.append([ finallop, i, int(round(finaltime)), list(set(finalip))])
			delays.append(int(round(finaltime)))

ip_locater = qqip.IpLocater(r'%s/qqwry.db'% curdir)

unknown_time=0
unknown_count=0
alltime=[]
for i in delays_withip:
	address = ip_locater.getIpAddr(qqip.string2ip(i[1]))
	host=address.decode('gb18030').encode('utf8')
	host=host.split('/')
	host[0]=host[0].strip()
	host[0]=host[0].strip('CZ88.NET')
	host[1]=host[1].strip()
	host[1]=host[1].strip('CZ88.NET')
	in_a_prov=0
	for j in province:
		if j in host[0]: 
			procount[j][0]=procount[j][0]+1
			procount[j][1]=procount[j][1]+i[2]
			alltime.append(i[2])
			in_a_prov=1
			totalip=totalip+1
	if in_a_prov==0:
		unknown_time=unknown_time+i[2]		
		unknown_count=unknown_count+1
prov_delay=[]
prov_num=[]
for i in province:
	if procount[i][0]!=0:
		alltime.append( int(round(procount[i][1]/float(procount[i][0]))))
		prov_delay.append([int(round(procount[i][1]/float(procount[i][0]))), i])
		prov_num.append([procount[i][0]/float(totalip), i])
		procount[i]=[procount[i][0],int(round(procount[i][1]/float(procount[i][0])))]

f=open("avgstd.dat",'w')
f.write('平均值 %3d ms, 方差 %3d ms'%(numpy.average(alltime), numpy.std(alltime)))
f.close()

if unknown_count!=0:
	unknown_time=int(round(unknown_time/unknown_count))

#prov_delay.append([unknown_time, '未知'])
#prov_num.append([unknown_count, '未知'])
prov_delay.sort()
prov_num.sort()
prov_num.reverse()

f=open('%s/prov_delay.dat'%curdir,'w')
for i in prov_delay:
#	f.write("%d\t%s\n"%( i[0], prov_short[i[1]]))
	f.write("%d\t　%s\n"%( i[0], i[1]))
f.close()
	
f=open('%s/prov_num.dat'%curdir,'w')
for i in prov_num:
#	f.write("%d\t%s\n"%( i[0], prov_short[i[1]]))
	f.write("%f\t　%s\n"%( i[0], i[1]))
f.close()
	
mindelay=100
maxdelay=600
interval=10
xticks=50

bucket=[]

print 'Writing to delays.dat'

for i in range((maxdelay-mindelay)/interval):
	bucket.append(0)	

for i in delays:
	if i<maxdelay and i>=mindelay:
		bucket[(i-mindelay)/interval]=bucket[(i-mindelay)/interval]+1

totalip=sum(bucket)

f=open('%s/delays.dat'%curdir, 'w')
for i in range(len(bucket)):
	if (i*interval)%xticks==0:
		f.write( '%f\t%d\n' % (bucket[i]/float(totalip), mindelay+interval*i))
	else:
		f.write( '%f\n' % (bucket[i]/float(totalip)))
f.close()

